package com.queryBuilder.util;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.queryBuilder.db.DBHelper;

public class DataUtil {

	/**
	 * 保存访问者信息
	 * 
	 * @param request
	 */
	public static void saveVistor(HttpServletRequest request) {
		String ip = getIpAddr(request);
		AddressUtils addressUtils = new AddressUtils();
		Date date = new Date();

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String area = null;
		try {
			area = addressUtils.getAddress("ip=" + ip, "utf-8");
			DBHelper.executeSQL(ip, format.format(date), area);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 获取真正Ip地址的方法
	 * 
	 * @param request
	 * @return
	 */
	private static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取访问者信息
	 * 
	 * @return
	 */
	public static String getVistorCount() {
		int count = DBHelper.countVistor();
		return String.valueOf(count);
	}

	public List<Map<String, String>> orderVisDetail() {
		List<Map<String, String>> list = null;
		try {
			list = DBHelper.detailIps();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return list;
	}
}
